import sys
from PyQt6.QtCore import QByteArray, QBuffer,Qt
from PyQt6.QtGui import QPixmap, QIcon
from images import Base64Image
import base64

golbalIsInstallPkg=True
golbalImageBase64Dict={}
 
#获取QPixmap对象
def getQPixmap(imageName):
    global golbalIsInstallPkg 
    if golbalIsInstallPkg:
        return loadBase64Pixmap(imageName)
    else: 
        return QPixmap("./images/"+imageName)
    
#获取QIcon对象
def getQIcon(imageName):
    global golbalIsInstallPkg 
    if golbalIsInstallPkg:
        pixmap= loadBase64Pixmap(imageName)
        return QIcon(pixmap)
    else: 
        return QIcon("./images/"+imageName)
    
#获取StyleURI
def getImageStyleURI(imageName):

    global golbalIsInstallPkg 
    if False:
        # 创建 QPixmap
        pixmap=loadBase64Pixmap(imageName)
        postfix=imageName.split('.')[1]
        # 生成 data URI
        imageBase64Dict=Base64Image.base64ImageDict
        base64Data=imageBase64Dict[imageName]
        data_uri = f"data:image/{postfix};base64,{base64Data}"
        
        return data_uri
    else: 
        return "./images/"+imageName

def loadBase64Pixmap(imageName):

    imageBase64Dict=Base64Image.base64ImageDict
    base64Data=imageBase64Dict[imageName]
    # 将base64字符串解码为字节数据
    byteArray = QByteArray.fromBase64(bytes(base64Data, 'utf-8'))
    buffer = QBuffer(byteArray)
    buffer.open(QBuffer.OpenModeFlag.ReadOnly)
    pixmap = QPixmap()
    pixmap.loadFromData(buffer.data(), str(imageName).split('.')[1],Qt.ImageConversionFlag.AutoColor)
    buffer.close()
    return pixmap

def loadBase64():
    filePath='./images/Base64Image.py'
    global golbalImageBase64Dict 
    if len(golbalImageBase64Dict)==0:
        ##按行读取文件
        with open(filePath, 'r') as file:
            while True:
                line = file.readline()
                if not line:
                    break
                imageName=line.split(';')[1]
                base64Data=line.split(';')[3]

                golbalImageBase64Dict[imageName]=base64Data
    return golbalImageBase64Dict